package net.llz.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.llz.config.WeChatConfig;
import net.llz.mapper.UserMapper;
import net.llz.model.UserDO;
import net.llz.service.UserService;
import net.llz.util.HttpUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatConfig weChatConfig;

//    @Autowired
//    private  UserDO userDO;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDO saveWeChatUser(String code) {

       String accessTokenUrl =  String.format(WeChatConfig.getOpenAccessTokenUrl(),weChatConfig.getOpenAppid(),weChatConfig.getOpenAppsecret(),code);
       //获取access_token

        Map<String,Object> baseMap = HttpUtils.doGet(accessTokenUrl);
        if(baseMap == null || baseMap.isEmpty()){
            return null;
        }
        String accessToken = (String) baseMap.get("access_token");
        String openId = (String) baseMap.get("openid");

        //获取用户基础信息
        String userTokenUrl = String.format(WeChatConfig.getOpenUserInfoUrl(),accessToken,openId);
        Map<String,Object> baseUserMap = HttpUtils.doGet(userTokenUrl);
        if(baseUserMap ==null || baseUserMap.isEmpty()){
            return null;
        }

        Double sexTemp = (Double) baseUserMap.get("nickname");
        int sex = sexTemp.intValue();

        String nickname = (String) baseUserMap.get("nickname");
        String province  = (String) baseUserMap.get("province");
        String city  = (String) baseUserMap.get("city");
        String country   = (String) baseUserMap.get("country");
        String headimgurl   = (String) baseUserMap.get("headimgurl");

        StringBuffer sb= new StringBuffer(country).append("||").append(province).append("||").append(city);
        String finalAddress= sb.toString();

       // nickname  = new String(nickname.getBytes(StandardCharsets.UTF_8));
        try {
            nickname  = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
            finalAddress = new String(finalAddress.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


       UserDO userDO= UserDO.builder().name(nickname).headImg(headimgurl).sex(sex).city(city).createTime(new Date()).openid(openId).build();

        userMapper.insert(userDO);
        return userDO;
    }

    /**
     * 根据id查找信息
     * @param id
     * @return
     */
    @Override
    public UserDO findById(int id) {

        return userMapper.selectById(id);
    }
}
